<template>
  <PageContainer title="客服会话">
    <!-- 调试用：实时显示关键状态（可选，用于直观观察） -->
    <div style="padding: 10px; background: #fff; margin: 10px; border-radius: 4px;" v-if="isDev">
      <h4 style="margin: 0 0 8px; font-size: 14px; color: #666;">请不要骚扰人工客服，友好交流</h4>
    </div>

    <!-- 原有页面结构 -->
    <div class="chat-container">
      <!-- 顶部客服信息栏 -->
      <div class="chat-header">
        <div class="avatar">
          <img :src="adminAvatar" alt="客服头像" class="avatar-img" />
        </div>
        <div class="admin-info">
          <h3 class="admin-name">{{ adminNickname || '未知客服' }}</h3>
          <p 
            class="admin-status" 
            :class="getAdminStatusClass(adminStatus)"
          >
            {{ formatAdminStatus(adminStatus) }}
          </p>
        </div>
        <el-button type="text" @click="handleGoBack" class="back-btn">
          <el-icon><ArrowLeft /></el-icon> 返回客服列表
        </el-button>
      </div>

      <!-- 中间消息列表区域 -->
      <div class="chat-messages" ref="messageContainerRef">
        <div class="loading-skeleton" v-if="loadingHistory">
          <el-skeleton animation="wave" :rows="5" class="skeleton-item" />
        </div>
        <el-empty 
          description="暂无聊天记录，开始对话吧～" 
          v-else-if="messageList.length === 0 && !loadingHistory"
          class="empty-tip"
        />
        <div 
          class="message-item" 
          v-for="(msg, index) in messageList" 
          :key="msg._id || `msg-${index}`"
          :class="{
            'send-message': msg.senderType === currentUser.type,
            'receive-message': msg.senderType === targetAdmin.type
          }"
        >
          <div class="message-bubble">
            <p class="message-content">{{ msg.content }}</p>
            <div class="message-meta">
              <span class="send-time">{{ formatMessageTime(msg.sendTime) }}</span>
              <span 
                class="read-tag" 
                v-if="msg.senderType === currentUser.type"
              >
                {{ msg.isRead ? '已读' : '未读' }}
              </span>
            </div>
          </div>
        </div>
        <div class="load-more-wrap" v-if="hasMoreHistory && !loadingMore">
          <el-button 
            type="text" 
            @click="handleLoadMoreHistory"
            class="load-more-btn"
          >
            加载更多历史消息
          </el-button>
        </div>
        <div class="loading-more-tip" v-if="loadingMore">
          <el-loading-spinner size="18" />
          <span class="loading-text">加载中...</span>
        </div>
      </div>

      <!-- 底部输入框区域 -->
      <div class="chat-input-area">
        <el-input
          v-model="inputMessage"
          type="textarea"
          :rows="3"
          placeholder="请输入消息内容..."
          @keydown.enter.prevent="handleSendMessage"
          clearable
          class="message-input"
        />
        <el-button 
          type="primary" 
          @click="handleSendMessage"
          class="send-btn"
          :disabled="!inputMessage.trim() || !sessionId" 
        >
          发送
        </el-button>
      </div>
    </div>
  </PageContainer>
</template>

<script setup>
import { ref, onMounted, nextTick, computed, watch, onUpdated } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElEmpty, ElSkeleton, ElIcon } from 'element-plus';
import { ArrowLeft } from '@element-plus/icons-vue';
import PageContainer from '@/components/PageContainer.vue';
import { useUserStore } from '@/stores/user';
import { createSession, getMessageHistory, sendMessage, getServiceInfo } from '@/api/service';
import adminDefaultAvatar from '@/assets/service.jpg';

const isDev = import.meta.env.DEV;

// -------------------------- 1. 基础状态 + 调试专用状态 --------------------------
const route = useRoute();
const router = useRouter();
const userStore = useUserStore();
const messageContainerRef = ref(null);

// 调试专用：存储客服信息接口原始返回（用于定位数据结构问题）
const adminInfoRaw = ref({}); 
// 调试专用：存储会话创建接口原始返回
const sessionResRaw = ref({}); 

// 原有核心状态
const adminId = ref(route.params.id || '');
const sessionId = ref('');
const adminAvatar = ref(adminDefaultAvatar);
const adminNickname = ref('');
const adminStatus = ref('online');
const inputMessage = ref('');
const messageList = ref([]);
const loadingHistory = ref(true);
const loadingMore = ref(false);
const hasMoreHistory = ref(true);
const pagination = ref({ page: 1, pageSize: 20, total: 0, totalPage: 0 });

// -------------------------- 2. 调试专用：监听关键状态变化 --------------------------
// 监听 adminId 变化（确认路由参数是否正确传递）
watch(adminId, (newVal, oldVal) => {
  console.log('[调试] adminId 变化：', '旧值=', oldVal, '新值=', newVal);
  if (!newVal) {
    console.warn('[调试] adminId 为空！请检查路由参数是否传递');
  }
}, { immediate: true }); // 初始化时立即执行

// 监听 sessionId 变化（确认会话是否创建成功）
watch(sessionId, (newVal, oldVal) => {
  console.log('[调试] sessionId 变化：', '旧值=', oldVal, '新值=', newVal);
  if (!newVal && oldVal) {
    console.warn('[调试] sessionId 被清空！可能是会话创建后异常重置');
  }
}, { immediate: true });

// 监听 adminNickname 变化（确认客服昵称是否赋值）
watch(adminNickname, (newVal, oldVal) => {
  console.log('[调试] adminNickname 变化：', '旧值=', oldVal, '新值=', newVal);
  if (newVal === '未知客服' && adminInfoRaw.value.data?.nickname) {
    console.warn('[调试] 客服昵称仍为"未知客服"，但接口返回有 nickname：', adminInfoRaw.value.data.nickname);
  }
}, { immediate: true });

// -------------------------- 3. 原有工具函数 --------------------------
const currentUser = computed(() => ({
  id: userStore.user?.id || '',
  type: 'User'
}));
const targetAdmin = computed(() => ({
  id: adminId.value,
  type: 'Admin'
}));

const getAdminStatusClass = (status) => {
  switch (status) {
    case 'online': return 'status-online';
    case 'busy': return 'status-busy';
    case 'offline': return 'status-offline';
    default: return 'status-online';
  }
};

const formatAdminStatus = (status) => {
  const statusMap = { online: '在线', busy: '忙碌', offline: '离线' };
  return statusMap[status] || '在线';
};

const formatMessageTime = (timeStr) => {
  if (!timeStr) return '';
  const date = new Date(timeStr);
  return date.toLocaleString('zh-CN', {
    year: 'numeric', month: '2-digit', day: '2-digit',
    hour: '2-digit', minute: '2-digit'
  });
};

const scrollToLatestMessage = () => {
  nextTick(() => {
    if (messageContainerRef.value) {
      messageContainerRef.value.scrollTop = messageContainerRef.value.scrollHeight;
    }
  });
};

// -------------------------- 4. 调试专用：获取发送按钮禁用原因 --------------------------
const getDisableReason = () => {
  if (!inputMessage.value.trim() && !sessionId.value) {
    return '消息内容为空 + sessionId 为空';
  } else if (!inputMessage.value.trim()) {
    return '消息内容为空';
  } else if (!sessionId.value) {
    return 'sessionId 为空（会话未创建）';
  } else {
    return '无禁用原因（按钮应启用）';
  }
};

// -------------------------- 5. 核心业务逻辑 + 详细日志 --------------------------
const initChatSession = async () => {
  try {
    if (!adminId.value) {
      throw new Error('未获取到客服ID');
    }

    // 1. 获取客服信息（已正常返回“小美”）
    const adminInfoRes = await getServiceInfo({ adminId: adminId.value });
    if (adminInfoRes.data.code === '0000') {
      adminNickname.value = adminInfoRes.data.data.nickname;
      console.log('[调试] 客服昵称已赋值：', adminNickname.value);
    }

    // 2. 创建/复用会话（现在可正常接收所有业务响应）
    const sessionRes = await createSession({ adminId: adminId.value });
    console.log('[调试] createSession 完整响应：', sessionRes.data);

    // 处理“新会话（0000）”和“已有会话（2013）”
    if (sessionRes.data.code === '0000' || sessionRes.data.code === '2013') {
      const sessionData = sessionRes.data.data || {};
      if (!sessionData.sessionId) {
        throw new Error('会话响应中缺少 sessionId');
      }
      sessionId.value = sessionData.sessionId; // 成功赋值 sessionId
      console.log('[调试] sessionId 已赋值：', sessionId.value);

      // 3. 加载历史消息
      await loadChatHistory();
    } else {
      throw new Error(`会话创建业务失败：${sessionRes.data.msg}`);
    }

  } catch (err) {
    console.error('[调试] initChatSession 异常：', err.message || err);
    ElMessage.error(err.message || '进入会话失败');
  }
};
const loadChatHistory = async (page = 1) => {
  console.log('[调试] 开始执行 loadChatHistory，当前 sessionId：', sessionId.value, '页码：', page);
  if (!sessionId.value) {
    console.warn('[调试] loadChatHistory 被调用但 sessionId 为空，跳过执行');
    return;
  }

  loadingHistory.value = page === 1;
  loadingMore.value = page > 1;
  try {
    const res = await getMessageHistory({
      sessionId: sessionId.value,
      page,
      pageSize: pagination.value.pageSize
    });
    console.log('[调试] getMessageHistory 接口返回：', JSON.stringify(res));

    if (res.data.code !== '0000') {
      throw new Error(`[调试] 历史消息加载失败，code=${res.data.code}，msg=${res.data.msg}`);
    }

    const { list, pagination: resPagination } = res.data.data || { list: [], pagination: {} };
    pagination.value = resPagination;
    hasMoreHistory.value = pagination.value.page < pagination.value.totalPage;

    if (page === 1) {
  messageList.value = list; // 第一页：从旧到新的消息列表
    } else {
      messageList.value = [...messageList.value, ...list]; // 后续页：更晚的消息拼在后面
    }
  } catch (err) {
    console.error('[调试] loadChatHistory 执行异常：', err.message);
    ElMessage.error(err.message || '历史消息加载失败，请重试');
  } finally {
    loadingHistory.value = false;
    loadingMore.value = false;
  }
};

const handleLoadMoreHistory = () => {
  const nextPage = pagination.value.page + 1;
  console.log('[调试] 触发加载更多历史消息，下一页：', nextPage);
  loadChatHistory(nextPage);
};

const handleSendMessage = async () => {
  const messageContent = inputMessage.value.trim();
  console.log('[调试] 触发发送消息，内容：', messageContent, 'sessionId：', sessionId.value);

  if (!messageContent) {
    ElMessage.warning('消息内容不能为空');
    return;
  }
  if (!sessionId.value) {
    ElMessage.error('会话未初始化，无法发送消息');
    return;
  }
  if (!currentUser.value.id) {
    ElMessage.error('用户信息异常，请重新登录');
    router.push('/login');
    return;
  }

  try {
    const res = await sendMessage({
      sessionId: sessionId.value,
      senderType: currentUser.value.type,
      senderId: currentUser.value.id,
      receiverType: targetAdmin.value.type,
      receiverId: targetAdmin.value.id,
      content: messageContent
    });
    console.log('[调试] sendMessage 接口返回：', JSON.stringify(res));

    if (res.data.code !== '0000') {
      throw new Error(`[调试] 消息发送失败，code=${res.data.code}，msg=${res.data.msg}`);
    }

    inputMessage.value = '';
    messageList.value.push(res.data.data);
    scrollToLatestMessage();
  } catch (err) {
    console.error('[调试] handleSendMessage 执行异常：', err.message);
    ElMessage.error(err.message || '消息发送失败，请重试');
  }
};

const handleGoBack = () => {
  console.log('[调试] 触发返回客服列表，跳转路由：/article/service');
  router.push('/article/service');
};

// -------------------------- 6. 生命周期 + 初始化日志 --------------------------
onMounted(async () => {
  console.log('[调试] 组件挂载开始，当前路由参数：', JSON.stringify(route.params));
  console.log('[调试] 当前用户信息（Pinia）：', JSON.stringify(userStore.user));

  // 初始化用户信息
  await userStore.initUser();
  console.log('[调试] 执行 userStore.initUser 后，用户信息：', JSON.stringify(userStore.user));

  if (!currentUser.value.id) {
    ElMessage.error('请先登录');
    router.push('/login');
    return;
  }

  // 初始化会话
  await initChatSession();
  // 加载历史消息（若 initChatSession 已调用，可注释，避免重复）
  // await loadChatHistory();
});

// 组件更新时打印状态（可选，用于追踪动态变化）
onUpdated(() => {
  console.log('[调试] 组件更新，当前关键状态：', {
    adminNickname: adminNickname.value,
    sessionId: sessionId.value,
    inputMessage: inputMessage.value,
    sendBtnDisabled: !inputMessage.value.trim() || !sessionId.value
  });
});
</script>



<style lang="scss" scoped>
/* 容器整体样式 */
.chat-container {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 120px); /* 适配屏幕高度（减去顶部导航栏高度） */
  background-color: #f5f7fa;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

/* 1. 顶部客服信息栏 */
.chat-header {
  display: flex;
  align-items: center;
  padding: 12px 20px;
  background-color: #fff;
  border-bottom: 1px solid #eee;

  .avatar {
    width: 48px;
    height: 48px;
    border-radius: 50%;
    overflow: hidden;
    margin-right: 16px;

    .avatar-img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }

  .admin-info {
    flex: 1;

    .admin-name {
      font-size: 16px;
      font-weight: 500;
      margin: 0 0 4px;
      color: #333;
    }

    .admin-status {
      font-size: 12px;
      padding: 2px 6px;
      border-radius: 4px;
      display: inline-block;
    }

    .status-online {
      background-color: #e1f3d8;
      color: #67c23a;
    }

    .status-busy {
      background-color: #fff3cd;
      color: #e6a23c;
    }

    .status-offline {
      background-color: #f5f5f5;
      color: #909399;
    }
  }

  .back-btn {
    color: #409eff;
    font-size: 14px;

    &:hover {
      color: #66b1ff;
    }
  }
}

/* 2. 中间消息列表区域 */
.chat-messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 16px;

  /* 加载骨架屏 */
  .loading-skeleton {
    margin-bottom: 20px;

    .skeleton-item {
      width: 100%;
      margin-bottom: 12px;
    }
  }

  /* 无消息提示 */
  .empty-tip {
    margin: auto;
  }

  /* 消息项通用样式 */
  .message-item {
    display: flex;
    max-width: 70%; /* 消息气泡最大宽度 */

    .message-bubble {
      padding: 12px 16px;
      border-radius: 16px;
      box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);

      .message-content {
        margin: 0 0 8px;
        line-height: 1.5;
        color: #333;
      }

      .message-meta {
        display: flex;
        align-items: center;
        justify-content: flex-end;
        font-size: 11px;
        gap: 8px;
      }

      .send-time {
        color: #909399;
      }

      .read-tag {
        color: #909399;
      }
    }
  }

  /* 发送方消息（右对齐） */
  .send-message {
    align-self: flex-end;

    .message-bubble {
      background-color: #409eff;

      .message-content {
        color: #fff;
      }

      .message-meta {
        .send-time,
        .read-tag {
          color: #e6f4ff;
        }
      }
    }
  }

  /* 接收方消息（左对齐） */
  .receive-message {
    align-self: flex-start;

    .message-bubble {
      background-color: #fff;
    }
  }

  /* 加载更多 */
  .load-more-wrap {
    align-self: center;
    margin-top: 8px;

    .load-more-btn {
      color: #409eff;
      font-size: 14px;
    }
  }

  .loading-more-tip {
    align-self: center;
    display: flex;
    align-items: center;
    gap: 8px;
    color: #909399;
    padding: 8px 0;

    .loading-text {
      font-size: 12px;
    }
  }
}

/* 3. 底部输入框区域 */
.chat-input-area {
  padding: 16px 20px;
  background-color: #fff;
  border-top: 1px solid #eee;
  display: flex;
  gap: 12px;

  .message-input {
    flex: 1;

    textarea {
      resize: none;
      border-radius: 8px;
      font-size: 14px;
    }
  }

  .send-btn {
    width: 100px;
    align-self: flex-end;
    border-radius: 8px;
  }
}
</style>